package com.srit.system.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.srit.core.bean.Page;
import com.srit.system.bean.GridAttrRel;
import com.srit.system.dao.GridAttrRelDao;

@Service
public class GridAttrRelDaoImpl implements GridAttrRelDao {

	@Autowired(required = true)
	private JdbcTemplate jdbcTemplate;

	@Override
	public int getMaxId() {
		String sql = "select max(id) from TC_GRIDATTRREL";
		return jdbcTemplate.queryForInt(sql);
	}

	@Override
	public void save(GridAttrRel rel) {
		String sql = "insert into TC_GRIDATTRREL (ID,GRIDID,ATTRID,HTMLNAME,HTMLID,TITLE,SHOWNAME,WIDTH) "
				+ "values(SEQ_TC_GRIDATTRREL.nextval,?,?,?,?,?,?,?)";
		jdbcTemplate.update(
				sql,
				new Object[] { rel.getGridId(), rel.getAttrId(),
						rel.getHtmlName(), rel.getHtmlId(), rel.getTitle(),
						rel.getShowName(), rel.getWidth() });
	}

	@Override
	public void update(GridAttrRel rel) {
		String sql = "update TC_GRIDATTRREL set GRIDID=?,ATTRID=?,HTMLNAME=?,HTMLID=?,TITLE=?,SHOWNAME=?,WIDTH=? where id=? ";
		jdbcTemplate.update(
				sql,
				new Object[] { rel.getGridId(), rel.getAttrId(),
						rel.getHtmlName(), rel.getHtmlId(), rel.getTitle(),
						rel.getShowName(), rel.getWidth(), rel.getId() });
	}

	@Override
	public GridAttrRel getById(Integer id) {
		String sql = "select * from TC_GRIDATTRREL where id=?";
		return jdbcTemplate.queryForObject(sql, new Object[] { id },
				new GridAttrRowMapper());
	}

	@Override
	public List<GridAttrRel> getListByGridId(int gridId) {
		String sql = "select * from TC_GRIDATTRREL where gridId=?";
		return jdbcTemplate.query(sql, new Object[] { gridId },
				new GridAttrRowMapper());
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void page(Page page) {
		// TODO Auto-generated method stub

	}

}

class GridAttrRelResultSetExtractor implements ResultSetExtractor {
	@Override
	public Object extractData(ResultSet rs) throws SQLException,
			DataAccessException {
		GridAttrRel gar = new GridAttrRel();
		gar.setId(rs.getInt("ID"));
		gar.setAttrId(rs.getInt("ATTRID"));
		gar.setHtmlId(rs.getString("HTMLID"));
		gar.setHtmlName(rs.getString("HTMLNAME"));
		gar.setShowName(rs.getString("SHOWNAME"));
		gar.setTitle(rs.getString("TITLE"));
		gar.setWidth(rs.getString("WIDTH"));
		return gar;
	}
}

class GridAttrRowMapper implements RowMapper {
	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		GridAttrRelResultSetExtractor extractor = new GridAttrRelResultSetExtractor();
		return extractor.extractData(rs);
	}

}
